/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rmsdao;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;
import rmsbean.UsuarioBean;

/**
 *
 * @author luis
 */
public class UsuarioDAO {

    private static final String RMSSTORE = "RMSUSUARIO";
    private RecordStore agendaRMS;

    public void open() throws RecordStoreException {
        this.agendaRMS = RecordStore.openRecordStore(RMSSTORE, true);
        System.out.println("USUARIO CRIOU");
    }

    public void close() throws RecordStoreNotOpenException, RecordStoreException {
        agendaRMS.closeRecordStore();
    }

    public void clear() throws RecordStoreException {
        RecordStore.deleteRecordStore(RMSSTORE);
    }

    public void insert(UsuarioBean usuario) throws IOException, RecordStoreNotOpenException, RecordStoreException {
        try {
            
        this.open();
        
        ByteArrayOutputStream Byteops = new ByteArrayOutputStream();
        DataOutputStream Dataops = new DataOutputStream(Byteops);
        Dataops.writeUTF(usuario.getLogin());
        Dataops.writeUTF(usuario.getSenha());
        Dataops.flush();
        byte[] usr = Byteops.toByteArray();
        agendaRMS.addRecord(usr, 0, usr.length);
        Byteops.close();
        Dataops.close();
        System.out.println("tamanho" + agendaRMS.getNumRecords());
        
        this.close();
        
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        
    }

    public void delete(UsuarioBean usuario) throws RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException {
        this.open();
        agendaRMS.deleteRecord(usuario.getCod());
        this.close();
    }

    public void update(UsuarioBean usuario) throws IOException, RecordStoreNotOpenException, RecordStoreException {
        this.open();
        byte[] registroBytes = usuario.getBytes();
        agendaRMS.setRecord(usuario.getCod(), registroBytes, 0, registroBytes.length);
        this.close();
    }

    

    
}